package com.fastCms.business.frame.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fastCms.business.frame.constant.CommonConst;
import com.fastCms.business.frame.pojo.InitEntity;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Base64Utils;

import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * @Description 常用
 * @Param
 * @Return
 * @Date 2019/3/8 下午5:12 lsquan
 */
public class CommonsUtil {
    public static final String ALL_CHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String SYMBOLS = "0123456789"; // 数字
    private static final String ENGLISHS = "abcdefghijklmnopqrstuvwxyz"; //小写字母
    private static final String ENGLISH_ALLCHAR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 纯字母


    /**
     * 解密前端传过来的base64加密后的密码,变换成真实密码
     *
     * @return
     */
    public static String decodeBase64Pwd(
        String encryptData) {
        String pwdStr = new String(Base64Utils.decodeFromString(encryptData));
        String twoPwsStr = new String(Base64Utils.decodeFromString(pwdStr));
        if (twoPwsStr.contains("@")) {
            String[] splitResult = twoPwsStr.split("@");
            if (splitResult.length >= 2) {
                return splitResult[1];
            }

        }
        return encryptData;
    }

    /**
     * 得到32位uuid
     *
     * @return
     */
    public static String getUUID() {
        String uuid = UUID.randomUUID().toString(); //获取UUID并转化为String对象
        uuid = uuid.replace(CommonConst.TRANSVERSE_LINE, CommonConst.EMPTY);//因为UUID本身为32位只是生成时多了“-”，所以将它们去点就可
        return uuid;
    }

    /**
     * 初始加密密码
     *
     * @return
     */
    public static String getInitEncryptPwd() {
        return new Md5Hash(CommonConst.USER_MANAGER.INIT_PASSWORD, CommonConst.USER_MANAGER.PWD_PRIVATE_KEY, 1024).toBase64();
    }

    /**
     * 获取时间戳+6位随机数
     *
     * @return
     */
    public static String getNewName() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(new Date()) + getRandomNum(6) + getUUID();
    }

    /**
     * 生成普通会员卡规则
     *
     * @return
     */
    public static String getCardNumber() {
        StringBuffer stringBuffer = new StringBuffer("VP");
        SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyHHmmss");
        String format = sdf.format(new Date());
        stringBuffer.append(format);
        stringBuffer.append(getRandomNum(4));
        return stringBuffer.toString();
    }

    /**
     * @Description 生成付费会员卡订单号
     * @Param
     * @Return java.lang.String
     * @Date 2019/4/10 下午5:59 lsquan
     */
    public static String getDisCardOrderNumber() {
        StringBuffer stringBuffer = new StringBuffer("DVP");
        SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyHHmmss");
        String format = sdf.format(new Date());
        stringBuffer.append(format);
        stringBuffer.append(CommonsUtil.getRandomNum(4));
        return stringBuffer.toString();
    }

    /**
     * @Description 生成企业订单号
     * @Param
     * @Return java.lang.String
     * @Date 2019/4/10 下午5:59 lsquan
     */
    public static String getCompOrderNumber() {
        StringBuffer stringBuffer = new StringBuffer("OCP");
        SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyHHmmss");
        String format = sdf.format(new Date());
        stringBuffer.append(format);
        stringBuffer.append(CommonsUtil.getRandomNum(4));
        return stringBuffer.toString();
    }

    /**
     * @Description 生成订单号
     * @Param
     * @Return java.lang.String
     * @Date 2019/4/10 下午5:59 lsquan
     */
    public static String getOrderNumber(String numberCode) {
        StringBuffer stringBuffer = new StringBuffer(numberCode);
        SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyHHmmss");
        String format = sdf.format(new Date());
        stringBuffer.append(format);
        stringBuffer.append(CommonsUtil.getRandomNum(4));
        return stringBuffer.toString();
    }

    /**
     * @Description 生成商城子订单号
     * @Param
     * @Return java.lang.String
     * @Date 2019/4/10 下午5:59 lsquan
     */
    public static String getItemOrderNumber(String orderNumber) {
        return orderNumber + CommonsUtil.getRandomNum(4);
    }


    /**
     * 生成商品编号
     *
     * @return
     */
    public static String getProductNumber() {
        StringBuffer stringBuffer = new StringBuffer();
        SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyHHmmss");
        String format = sdf.format(new Date());
        stringBuffer.append(format);
        stringBuffer.append(getRandomNum(4));
        return stringBuffer.toString();
    }

    /**
     * 初始化实体对象，给初始字段赋值
     *
     * @param targetObject
     * @param <T>
     * @return
     */
    public static <T extends Object> T initEntity(T targetObject) {

        InitEntity initEntity = new InitEntity(new Date(), CommonConst.STATE.VALID);
        BeanUtils.copyProperties(initEntity, targetObject);

        return targetObject;
    }


    /**
     * 获取随机数(数字）
     *
     * @return
     */
    public static String getRandomNum(int length) {
        // 如果需要4位，那 new char[4] 即可，其他位数同理可得
        char[] nonceChars = new char[length];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(new Random().nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }


    /**
     * 返回一个定长的随机字符串(包含大小写字母、数字).
     *
     * @param length 随机字符串长度
     * @return 随机字符串
     */
    public static String generateMixString(int length) {
        StringBuilder sb = new StringBuilder();
        SecureRandom random = new SecureRandom();
        for (int i = 0; i < length; i++) {
            sb.append(ALL_CHAR.charAt(random.nextInt(ALL_CHAR.length())));
        }
        return sb.toString();
    }

    /**
     * 返回一个定长的随机字符串(只包含大小写字母).
     *
     * @param length 随机字符串长度
     * @return 随机字符串
     */
    public static String generateEnglishChar(int length) {
        StringBuilder sb = new StringBuilder();
        SecureRandom random = new SecureRandom();
        for (int i = 0; i < length; i++) {
            sb.append(ENGLISH_ALLCHAR.charAt(random.nextInt(ENGLISH_ALLCHAR.length())));
        }
        return sb.toString();
    }

    /**
     * 返回一个定长的随机字符串(只包含小写字母).
     *
     * @param length 随机字符串长度
     * @return 随机字符串
     */
    public static String generateLowEnglishChar(int length) {
        return generateEnglishChar(length).toLowerCase();
    }

    public static void main(String[] args) {
//        for (int i = 0; i < 100; i++) {
//            System.out.println(getRandomNum(6));
//        }
        //      String productNumber = getProductNumber();

//        String result = decodeBase64Pwd("WlVSdGFYQXpkSGhyTmxrM1FtZzNUV1Y2V1hKVVpGRlhTRkJVTTFkSFNGUkFhR1ZoYkhSb2NISnZNakF4T1VCdFdUVlJlbEZxVTJGRmMwaHRTMXBhVWxjNFJVSmlaRXRUWmxOemVIaFFhQT09");
//
//        System.out.println(result);//验证码长度

        System.out.println(getInitEncryptPwd());

        //System.out.println(DateUtils.addMinutes(new Date(), CommonConst.VERIFICATION.VALID_MILLION));//时间累加
    }


    /**
     * 将oldValue的值复制到newValue 有的覆盖没有的不变
     *
     * @param newValue
     * @param oldValue
     * @param <T>
     * @return
     */
    public static <T extends Object> T copyProperties(Object oldValue, T newValue, Class<T> clazz) {
        Map<String, Object> oldMap = JSON.parseObject(JSON.toJSONString(oldValue), Map.class);
        Map<String, Object> newMap = JSON.parseObject(JSON.toJSONString(newValue), Map.class);
        newMap.putAll(oldMap);
        return JSON.parseObject(JSON.toJSONString(newMap), clazz);
    }

    /**
     * 是否是json
     *
     * @param content
     * @return
     */
    public static boolean isJsonObject(String content) {
        try {
            JSONObject.parseObject(content);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}
